/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.crypto;

import com.sentry.commons.utils.Exceptions;

import org.apache.commons.codec.binary.Hex;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;

/**
 * 支持SHA-1/SHA-256/SHA-512/MD5消息摘要的工具类.<br>
 * 
 * 默认返回字节数组，如果需要hex格式，可以使用 {@link Hex#encodeHex}来编码
 * 
 * @author WuBo (wub1@minshenglife.com)
 */
public class Digests {

    static enum DigestAlg {
        MD5("MD5"), SHA1("SHA-1"), SHA256("SHA-256"), SHA512("SHA-512");
        String value;

        DigestAlg(String alg) {
            this.value = alg;
        }
    }


    public static byte[] sha1(byte[] input) {
        return digest(input, DigestAlg.SHA1, null, 1);
    }

    public static byte[] sha256(byte[] input) {
        return digest(input, DigestAlg.SHA256, null, 1);
    }

    public static byte[] sha512(byte[] input) {
        return digest(input, DigestAlg.SHA512, null, 1);
    }

    public static byte[] md5(byte[] input) {
        return digest(input, DigestAlg.MD5, null, 1);
    }




    /**
     * 更加复杂的摘要算法方法
     * @param input 输入源
     * @param alg 算法 {@link DigestAlg}
     * @param salt 盐值
     * @param iterations 迭代次数
     * @return
     */
    public static byte[] digest(byte[] input, DigestAlg alg, byte[] salt,
            int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(alg.value);

            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            throw Exceptions.unchecked(e);
        }
    }


}
